package de.alex.schulzeit;
// TODO: Refactoring
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ViewFlipper;
import de.alex.schulzeit.db.DatabaseHelper;
import de.alex.schulzeit.db.Subjecttable;
import de.alex.schulzeit.preference.ListPreferenceMultiSelect;

public class Startpage extends Activity implements OnTouchListener {
	private String TAG = Startpage.class.getSimpleName();
	private int day = Date.getDay();
	private String[] schooldays;
	private DatabaseHelper db;
	private int hours = 10;
	private int orientation = 1;
	private float downXValue = 0;
	
	//int orientation = getResources().getConfiguration().orientation; // used for dynamic row add
   //test
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Cursor c;
    	Subjecttable subjectDb;
    	
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.orientation = getResources().getConfiguration().orientation;
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        schooldays = ListPreferenceMultiSelect.parseStoredValue(prefs.getString("schooldays", "1xxx2xxx3xxx4xxx5"));
        subjectDb = this.getSubjecttable();
        if (this.isInArray("2", schooldays)) {
			Log.d("JLADSF", "Ist vorhanden"); 
		}
        
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        	c = subjectDb.getAllTimeTableSubjects();
			this.createRowWeek(c);
			c.close();
		} else {
			// Register Touch Event for the vertical layout
	        LinearLayout layMain = (LinearLayout) findViewById(R.id.layout_day);
	        layMain.setOnTouchListener((OnTouchListener) this);
	        for (int i = 0; i < 5; i++) {
	        	if (this.isInArray(Integer.toString(this.day), schooldays)) {
	        		this.setDayText();
	    			c = subjectDb.getTimeTableSubjectsForDay(this.day);
	    			Log.d(TAG, "" + c.getCount());
	    			this.createRowDay(c);
	    			c.close(); 
	    			break;
				} else {
					day ++;
					if (day >6) {
						day = 1;
					}
				}
			}
			
		}
        db.close();
    }
    
    /**
     * Creates the mainmenu
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.mainmenu, menu);
    	super.onCreateOptionsMenu(menu);
    	return true;
    }
    
    /**
     * Responsible to take action when an option item is clicked
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.Settings:
			Intent settingsIntent = new Intent(Startpage.this, Settings.class);
			Startpage.this.startActivity(settingsIntent);
			break;
		default:
			break;
		}
    	return super.onOptionsItemSelected(item);
    }
    
    /**
     * Creates the contextMenu
     */
    public void onCreateContextMenu(ContextMenu menu, View v, 
    		ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	getMenuInflater().inflate(R.menu.contextmenu, menu);
    	//TODO: Maybe add different contextMenus
    }
    
    /**
     * Responsible to take actoin when an context item is clicked
     */
    public boolean onContextItemSelected(MenuItem item) {
    	//TODO: add all cases and programm them out
    	switch (item.getItemId()) {
		case R.id.add_subject:
			
			break;
		case R.id.edit_subject:
			break;
		}
    	return super.onContextItemSelected(item);
    }
    
    public boolean onTouch(View arg0, MotionEvent arg1) {

        // Get the action that was done on this touch event
        switch (arg1.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            {
                // store the X value when the user's finger was pressed down
                downXValue = arg1.getX();
                break;
            }

            case MotionEvent.ACTION_UP:
            {
                // Get the X value when the user released his/her finger
                float currentX = arg1.getX();            

                // going backwards: pushing stuff to the right, swipe right to left 
                if (downXValue < currentX && currentX - downXValue > 150)
                {
                	this.setContentView(R.layout.main);
                	// Register Touch Event for the vertical layout
                    LinearLayout layMain = (LinearLayout) findViewById(R.id.layout_day);
                    layMain.setOnTouchListener((OnTouchListener) this); 
                	
                    // Get a reference to the ViewFlipper
                     ViewFlipper vf = (ViewFlipper) findViewById(R.id.day_details);
                     // Set the animation
                     vf.setInAnimation(arg0.getContext(), R.anim.slide_in_left);
                     vf.setOutAnimation(arg0.getContext(), R.anim.slide_out_left);	                      // Flip!
                     vf.showPrevious();
                     
                     for (int i = 0; i < 5; i++) {
	                     this.day -=1;
	                     if (this.day <1) {
							this.day=6;
	                     }
	                     this.setDayText();
	                     if (this.isInArray(Integer.toString(this.day), schooldays)) {
	                    	 this.createRowDay(this.getSubjecttable().getTimeTableSubjectsForDay(this.day));
	                     }
                     }
                     
                     
                }

                // going forwards: pushing stuff to the left
                if (downXValue > currentX && this.downXValue - currentX >150)
                {
                	this.setContentView(R.layout.main);
//                  Register Touch Event for the vertical layout
                    LinearLayout layMain = (LinearLayout) findViewById(R.id.layout_day);
                    layMain.setOnTouchListener((OnTouchListener) this); 
                    
                    // Get a reference to the ViewFlipper
                    ViewFlipper vf = (ViewFlipper) findViewById(R.id.day_details);
                     // Set the animation
                    vf.setInAnimation(arg0.getContext(), R.anim.slide_in_right);
                    vf.setOutAnimation(arg0.getContext(), R.anim.slide_out_right);	
                    vf.showNext();
                    
                    //TODO: Fehler in der Schleife
                    Log.d("ASDF", "" + this.day);
                    for (int i = 0; i < 5; i++) {
                    	Log.d("ASDF", "" + this.day);
	                    this.day +=1;
	                    Log.d("ASDF", "" + this.day);
	                    if (this.day >6) {
							this.day = 1; 
	                    }
						this.setDayText();
	                     if (this.isInArray(Integer.toString(this.day), schooldays)) {
	                    	 Log.d("ASDF", "Gefunden");
	                    	 this.createRowDay(this.getSubjecttable().getTimeTableSubjectsForDay(this.day));
	                    	 break;
						}
	                     Log.d("ASDF", "Schleifenende"); 
                    }
                }
               
            }
        }

        // if you return false, these actions will not be recorded
        return true;
    }

    private Subjecttable getSubjecttable() {
    	Subjecttable subjectDb;
    	
    	db = new DatabaseHelper(this);
        subjectDb = new Subjecttable(db);
        db.close();
        return subjectDb;
    }
    
    private void setDayText() {
		TextView dayString = (TextView) findViewById(R.id.weekday);
    	dayString.setText(getResources().getString(Date.getDay(this.day)));
    }
    
    /**
     * Dynamically add Rows for the Day Table for the specific day
     * 
     * @param Cursor c
     */
    private void createRowDay(Cursor c) {
    	TableLayout table = (TableLayout) findViewById(R.id.tableDay);
    	
    	for (int i = 1; i <= hours; i++) {
    		TableRow tr = new TableRow(this);
    		c.moveToPosition(-1);
            tr.setLayoutParams(new LayoutParams(
                                LayoutParams.FILL_PARENT,
                                LayoutParams.WRAP_CONTENT));
            TextView hour = new TextView(this);
            hour.setText(Integer.toString(i));
            
            TextView subject = new TextView(this);
            if (c.getCount() != 0) {
            	while (c.moveToNext()) {
            		Log.d(TAG, "In der Schleife");
					if (i == c.getInt(4) && day == c.getInt(3)) { //column 3 = tag, column 4 = stunde
						subject.setText("yep");
						Log.d(TAG, "Gefunden");
						break;
					}
	            }
            } else {
            	subject.setText("none");
						Log.d(TAG, "Nicht vorhanden");
            }
            tr.addView(hour);
            tr.addView(subject);
            table.addView(tr);
		}
    	c.close();
    }
    
    private void createRowWeek(Cursor c) {
    	TableLayout table = (TableLayout) findViewById(R.id.tableWeek);
    	for (int i = 1; i <= 5; i++) {
    		
    	}
    }
    
    private boolean isInArray(String x, String[] y) {
    	
    	for(int i = 0; i < y.length; i++) {
            if(x.equals(y[i])) {
               return true;
            }
         
    	} 
    	return false;
    }
}